package handler

import (
	"github.com/gin-gonic/gin"
	"news-mgmt-sys/cache"
	"news-mgmt-sys/model"
	"news-mgmt-sys/pkg"
	"time"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	if tel == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "user_login_" + tel
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,已封禁",
		})
		return
	}
	var user model.User
	err := model.DB.Where("tel=?", tel).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "电话号查询错误,登录失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在,登录失败",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,账号禁封两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误,请重新输入",
		})
		return
	}
	token := pkg.TokenHandler(tel)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"data":  user,
		"token": token,
	})
	return
}
func Info(c *gin.Context) {
	uid, _ := c.Get("uid")
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "jwt解密成功",
		"uid":  uid,
	})
	return
}
